package com.example.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadSocket {
    public static void main(String[] args) {
        Common common = new Common();
        Inc inc = new Inc(common);
        Desc desc = new Desc(common);
        new Thread(inc,"inc").start();
        new Thread(inc,"inc2").start();
        new Thread(desc,"desc").start();
        new Thread(desc,"desc2").start();
    }
}
class Inc implements Runnable{
    public Common common;
    public Inc(Common common){
        this.common=common;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            common.IncNum();
        }
    }
}
class Desc implements Runnable{
    public Common common;
    public Desc(Common common){
        this.common=common;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
             common.desc();
        }
    }
}
class Common {
    private Integer count = 0;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public  void IncNum() {
        lock.lock();
        try {
            while (count>0) {
                condition.await();
            }
            System.out.println("生产者" + ++count);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public  Integer desc() {
        lock.lock();
        try {
            while (count ==0) {
                condition.await();
            }
            System.out.println("消费者消费" + count--);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            return count;
        }
    }
}
